﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using shenghua.Authorization.Users;
using shenghua.Common.WordNodes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Basics.FileSystem
{
    public class FileSystemManager : WordNodeManager<FileItem>
    {
        public FileSystemManager(IRepository<FileItem> fileItemRepository)
            :base(fileItemRepository)
        {
            Sortable = false;
        }

        public async Task<FileItem> SaveFlie(User user, string fileName, byte[] bytes, int? parentId = null)
        {
            if(parentId != null)
            {
                await Get((int)parentId);
            }

            FileInfo fileInfo = new FileInfo(fileName);

            string path = AmuTools.Normal.DatePathHelper.SaveFile(fileInfo.Extension, bytes);

            FileItem fileItem = new FileItem
            {
                UserId = user.Id,
                DisplayName = fileName,
                Size = bytes.Length,
                Path = path,
                ParentId = parentId
            };

            await base.Add(fileItem);

            return fileItem;
        }

        public async Task<FileItem> CreateFile(long userId, FileItem fileItem, int? parentId = null)
        {
            fileItem.UserId = userId;
            fileItem.ParentId = parentId;
            fileItem.IsFolder = false;
            await base.Add(fileItem);
            return fileItem;
        }

        public async Task<FileItem> CreateFolder(long userId, FileItem fileItem, int? parentId = null)
        {
            fileItem.UserId = userId;
            fileItem.ParentId = parentId;
            fileItem.IsFolder = true;
            await base.Add(fileItem);
            return fileItem;
        }
    }
}
